$(function() {
    function split( val ) {
      return val.split( /,\s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }
	var OutPuturl = $(".searchInput").attr('url');
    $( ".searchInput" )
      // don't navigate away from the field on tab when selecting an item
      .bind( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB &&
            $( this ).data( "ui-autocomplete" ).menu.active ) {
          event.preventDefault();
        }
      })
      .autocomplete({
        source: function( request, response ) {
          $.getJSON(OutPuturl, {
            term: extractLast( request.term )
          }, response );
        },
        search: function() {
          // custom minLength
          var term = extractLast( this.value );
          if ( term.length < 3 ) {
            return false;
          }
		  $('div#payment-modes').hide();
        },
        focus: function() {
          // prevent value inserted on focus
          return false;
        },
        select: function( event, ui ) {
          var terms = split( this.value );
          // remove the current input
          terms.pop();
          // add the selected item
          terms.push( ui.item.value );
          // add placeholder to get the comma-and-space at the end
          terms.push( "" );
          this.value = terms.join( "" );
		  get_down(this.value);
          return false;
        }
      });
	  
	  //autocomplete search for students fees
	  var forFees = $(".searchFee").attr('url');
	  $( ".searchFee" ).autocomplete_sanitizer({url:forFees});
      

	$( "button.add" ).button().click(function( event ) {
		event.preventDefault();
		var newOutPuturl = $(".searchFee").attr('url');
		var numItems = $('#dynapage .input-fields-clone').length;
		
		var cloned_fields = $('.input-fields').clone()
						.attr("id", "input-fields-clone_"+numItems)
						 .attr("class", "input-fields-clone")
						 .appendTo('#dynapage')
						 .find('input:text,select,input[type=hidden]')
						 .attr("id", "input-fields-text-clone_"+numItems);
						 
		var	appended_clones = $('#dynapage');
			appended_clones.find('input:text.search').last().val('').autocomplete_sanitizer({url:forFees});
			appended_clones.find('input:text.quantity').last().val('').quantity_binder();
			appended_clones.find('input:text.unitprice').last().val('');
			appended_clones.find('input:text.total').last().val('');
	  });

	$( "button.del" ).button().click(function( event ) {
		event.preventDefault();
		$('#dynapage .input-fields-clone:last-child').remove();
	  });
	  
	 $( "button.clrs" ).button().click(function( event ) {
		event.preventDefault();
		$('#dynapage .input-fields-clone').remove();
	  });
	  
	  
	  //
	  
	  $('input:text.quantity').quantity_binder();
	  $('input:text.unitprice').quantity_binder();
	  
	  $('input:text.unitprice').on('focus change hover keyup load',function(){
			var class_name = $(this).attr('id');
			var quantity = $("input[type=text]#"+class_name+".quantity").attr('value');
			var price = $("input[type=text]#"+class_name+".unitprice").attr('value');
			
			$("input[type=text]#"+class_name+":disabled").val(numberWithCommas(roundToTwo(+quantity * +price)));
	  });
	  
	 $(".fee-select").change(function(){
		var value =$('option:selected', this).attr('others');
		var class_name = $(this).attr('id');
		// var price = $(".input-fields input[type=text].unitprice").val();
		$("input#"+class_name +".unitprice").val(roundToTwo(value));
	 });
});

function numberWithCommas(x) {
	var parts = x.toString().split(".");
	parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
	return parts.join(".");
}
		
function roundToTwo(num) {    
	return +(Math.round(num + "e+2")  + "e-2");
}
  
function get_down(x)
{
	var url = $('div#payment-modes').attr('url');
	// console.log(url);
	$.get( url, { id: x } ).done(function( data ){
		 $('div#payment-modes').show().html(data);
		 // console.log(data);
	});
}

function enable_autocomplete(InputField) {
    $(InputField).autocomplete('enable');
}

(function( $ ){
	function split( val ) {
      return val.split( /,\s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }
    $.fn.autocomplete_sanitizer = function(options) {
	var settings = $.extend({
            // These are the defaults.
            url: ""
    }, options );
	
	
	$(this).bind( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB &&
            $( this ).data( "ui-autocomplete" ).menu.active ) {
          event.preventDefault();
        }
      })
      .autocomplete({
        source: function( request, response ) {
          $.getJSON(settings.url, {
            term: extractLast( request.term )
          }, response );
        },
        search: function() {
          // custom minLength
          var term = extractLast( this.value );
          if ( term.length < 3 ) {
            return false;
          }
        },
        focus: function() {
          // prevent value inserted on focus
          return false;
        },
        select: function( event, ui ) {
          var terms = split( this.value );
          // remove the current input
          terms.pop();
          // add the selected item
          terms.push( ui.item.value );
          // add placeholder to get the comma-and-space at the end
          terms.push( "" );
          this.value = terms.join( "" );
		  
		  $('input#'+$(this).attr('id')+'.unitprice').val(ui.item.id);
		  $('input[type=hidden]#'+$(this).attr('id')).val(ui.item.fee_id);
          return false;
        }
      });
    };
})( jQuery );


(function( $ ){
    $.fn.quantity_binder = function(options) {
		var settings = $.extend({
				// These are the defaults.
				class: ""
		}, options );
		$(this).on('focus change hover keyup load',function(){
			var class_name = $(this).attr('id');
			// console.log(class_name);
			var quantity = $("input#"+class_name+".quantity").val();
			var price = $("input#"+class_name+".unitprice").val();
			$("input#"+class_name+".total:disabled").val(numberWithCommas(roundToTwo(+quantity * +price)));
		});
    };
})( jQuery );
